package org.example.managere.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义错误处理控制器
 * 用于处理各种HTTP错误，特别是前端路由与后端API路径冲突的情况
 */
@Controller
public class CustomErrorController implements ErrorController {

    /**
     * 处理错误请求
     * 对于API路径，返回JSON错误响应
     * 对于前端路由，重定向到index.html
     */
    @RequestMapping("/error")
    @ResponseBody
    public Object handleError(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("jakarta.servlet.error.status_code");
        String path = (String) request.getAttribute("jakarta.servlet.error.request_uri");
        String message = (String) request.getAttribute("jakarta.servlet.error.message");
        
        if (path == null) {
            path = request.getRequestURI();
        }
        
        // 确保状态码不为空
        if (statusCode == null) {
            statusCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
        }
        
        // 如果是前端路由路径，返回index.html
        if (path != null && !path.startsWith("/api/") && !path.startsWith("/css/") && 
                !path.startsWith("/js/") && !path.startsWith("/images/") && !path.endsWith(".ico")) {
            return "forward:/index.html";
        }
        
        // 如果是API请求，返回JSON错误信息
        Map<String, Object> errorDetails = new HashMap<>();
        errorDetails.put("status", statusCode);
        errorDetails.put("error", HttpStatus.valueOf(statusCode).getReasonPhrase());
        errorDetails.put("path", path);
        
        if (message != null && !message.isEmpty()) {
            errorDetails.put("message", message);
        } else {
            errorDetails.put("message", "请求处理失败");
        }
        
        return new ResponseEntity<>(errorDetails, HttpStatus.valueOf(statusCode));
    }
} 